package com.wang.socket;

import com.alibaba.fastjson.JSON;
import com.wang.pojo.CustomerQuestion;
import com.wang.response.PageResult;
import com.wang.service.CustomerQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
//@Component
//@ServerEndpoint(value = "/onLineService")
public class MyWebSocket {

    // 全部在线会话 PS: 基于场景考虑 这⾥使⽤线程安全的Map存储会话对象。
    //记录当前在线连接数
    private static Map<String, Session> onlineSessions = new
            ConcurrentHashMap<>();
    private Session _session;

    //连接建立成功调用的方法
    @OnOpen
    public void onOpen(Session session,String username) {

        this._session = session;
        onlineSessions.put(session.getId(), session);
        try {
            //sendMessageAll("欢迎光临寒舍！！！");
            sendMessage(session,"您好,您想咨询什么问题");
        }catch (Exception e) {
            log.error("onOpen", e);
        }
        log.info("有新连接加⼊，当前在线数为" + onlineSessions.size());
    }

    //连接关闭调用的方法
    @OnClose
    public void onClose(Session session) {
        onlineSessions.remove(session.getId());
        log.info("有⼀连接关闭！当前在线数为" + onlineSessions.size());
    }

    //收到客户端消息后调用的方法
    //后台收到客户端发送过来的消息
    //消息的中转站
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        //sendMessageAll(session.getId() + ":" + message);
        sendMessage(session,"您是想问"+message);
        log.info("来⾃客户端 " + " 的消息:" + message);
    }
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("LoginResultWebSocket 发⽣错误");
        error.printStackTrace();
    }
    //服务端发送消息给客户端
    public void sendMessage(Session session, String message) throws
            IOException {
        session.getBasicRemote().sendText(message);
    }
    //服务端发送消息给所有客服端
    public void sendMessageAll(String message) {
        for(String key : onlineSessions.keySet()){
            Session session = onlineSessions.get(key);
            try {
                sendMessage(session, message);
            }
            catch (Exception e) {
                log.error("sendMessageAll", e);
            }
        }
    }



}
